package com.todo.pro.storage.impl;

import java.io.ByteArrayInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.todo.pro.storage.FileStorage;
import com.todo.pro.storage.QiNiuConfig;

public class QiNiuStorage implements FileStorage, InitializingBean {

	Logger logger = LoggerFactory.getLogger(QiNiuStorage.class);

	private QiNiuConfig qiNiuConfig;

	public void setQiNiuConfig(QiNiuConfig qiNiuConfig) {
		this.qiNiuConfig = qiNiuConfig;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
	}

	@Override
	public String initUpToken() {
		Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
		return auth.uploadToken(qiNiuConfig.getBucket());
	}
	
	@Override
	public boolean uploadImage(String path, byte[] bytes) {
		Auth auth = Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
		String upToken = auth.uploadToken(qiNiuConfig.getBucket(), path);
		Configuration cfg = new Configuration(Zone.zone0());
		UploadManager uploadManager = new UploadManager(cfg);
		ByteArrayInputStream byteInputStream = new ByteArrayInputStream(bytes);
		try {
			Response response = uploadManager.put(byteInputStream, path, upToken, null, null);
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			logger.info("UploadSuc >>>>> " + putRet.key + ":" + putRet.hash);
			return true;
		} catch (QiniuException ex) {
			ex.printStackTrace();
		}
		return false;
	}

}
